#include "Transfer.hpp"
#include <spdlog/spdlog.h>
#include <stdexcept>

const char* POSIX_QUEUE_NAME="/HBTY_MSGQUEUE_PROJECT";

Transfer::Transfer(std::function<std::string(std::string)> data_callback)
  : dataCallback(data_callback)
{
  queueFlag=mq_open(POSIX_QUEUE_NAME,O_CREAT | O_RDWR,S_IRUSR | S_IWUSR,nullptr);
  if(queueFlag==-1) throw std::runtime_error("无法创建消息队列");
  struct mq_attr attr;
  int ret=mq_getattr(queueFlag,&attr);
  if(ret==-1)
    throw std::runtime_error("无法获取消息队列属性");
  else
    spdlog::info("消息队列创建成功，消息大小为: {}",attr.mq_msgsize);
  dataReceiveBuffer=new char[attr.mq_msgsize];
  bufferSize=attr.mq_msgsize;
}

Transfer::~Transfer()
{
  spdlog::debug("Call ~Transfer");
  //关闭描述符
  mq_close(queueFlag);
  delete [] dataReceiveBuffer;
}

void Transfer::run()
{
  int ret;
  while(runFlag)
  {
    ssize_t ReceiveSize=mq_receive(queueFlag,dataReceiveBuffer,bufferSize,nullptr);
    if(runFlag==false) return;
    std::string returnVal=dataCallback(std::string(dataReceiveBuffer,ReceiveSize));
    spdlog::debug("Receive message data : {}",dataReceiveBuffer);
    ret=mq_send(queueFlag,returnVal.c_str(),returnVal.length()+1,0);
    if(runFlag==false) return;
    if(ret==0)
      spdlog::debug("Send message success : {}",returnVal);
    else
      spdlog::warn("Can't send message : {}",returnVal);
  }
}

void Transfer::stop()
{
  runFlag=false;
}
